"""
客户端管理路由
"""

from fastapi import APIRouter, HTTPException, Query
from typing import List, Optional, Dict, Any
import time

from ..models import (
    ClientsListResponse, ClientResponse, ClientRegisterRequest,
    BaseResponse, ErrorResponse
)
from ..storage import data_manager, ClientInfo
from ..logger import logger
from ..utils import generate_id

router = APIRouter()


@router.get("/clients", response_model=ClientsListResponse)
async def get_clients(
    status: Optional[str] = Query(None, description="状态过滤"),
    search: Optional[str] = Query(None, description="搜索关键词")
):
    """获取客户端列表"""
    try:
        # 从存储获取所有客户端
        clients = await data_manager.get_clients()
        
        # 应用过滤器
        filtered_clients = clients
        
        if status:
            filtered_clients = [c for c in filtered_clients if c.status == status]
            
        if search:
            search_lower = search.lower()
            filtered_clients = [
                c for c in filtered_clients 
                if search_lower in c.client_name.lower() 
                or search_lower in c.hostname.lower()
                or search_lower in c.client_id.lower()
            ]
        
        # 转换为响应模型
        client_responses = [
            ClientResponse(
                id=client.id,
                client_id=client.client_id,
                client_name=client.client_name,
                hostname=client.hostname,
                ip_address=client.ip_address,
                port=client.port,
                version=client.version,
                capabilities=client.capabilities,
                description=client.description,
                contact_info=client.contact_info,
                registered_at=client.registered_at,
                last_seen=client.last_seen,
                status=client.status
            )
            for client in filtered_clients
        ]
        
        return ClientsListResponse(
            clients=client_responses,
            total=len(client_responses),
            message=f"Found {len(client_responses)} clients"
        )
        
    except Exception as e:
        logger.error(f"Failed to get clients: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve clients")


@router.get("/clients/available")
async def get_available_clients():
    """获取可用的pyolo客户端"""
    try:
        clients = await get_pyolo_client_info()
        return {
            "success": True,
            "clients": clients,
            "total": len(clients)
        }
    except Exception as e:
        logger.error(f"Failed to get available clients: {e}")
        return {
            "success": False,
            "error": str(e),
            "clients": [],
            "total": 0
        }


@router.get("/clients/{client_id}", response_model=ClientResponse)
async def get_client(client_id: str):
    """获取指定客户端详情"""
    try:
        client = await data_manager.get_client_by_id(client_id)
        
        if not client:
            raise HTTPException(status_code=404, detail="Client not found")
        
        return ClientResponse(
            id=client.id,
            client_id=client.client_id,
            client_name=client.client_name,
            hostname=client.hostname,
            ip_address=client.ip_address,
            port=client.port,
            version=client.version,
            capabilities=client.capabilities,
            description=client.description,
            contact_info=client.contact_info,
            registered_at=client.registered_at,
            last_seen=client.last_seen,
            status=client.status
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get client {client_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve client")


@router.post("/clients/register", response_model=BaseResponse)
async def register_client(client_request: ClientRegisterRequest):
    """注册新客户端"""
    try:
        current_time = time.time()
        
        # 检查是否已存在相同client_id的客户端
        existing_client = await data_manager.get_client_by_client_id(client_request.client_id)
        
        if existing_client:
            # 更新现有客户端信息
            existing_client.client_name = client_request.client_name
            existing_client.hostname = client_request.hostname
            existing_client.ip_address = client_request.ip_address
            existing_client.port = client_request.port
            existing_client.version = client_request.version
            existing_client.capabilities = client_request.capabilities
            existing_client.description = client_request.description
            existing_client.contact_info = client_request.contact_info
            existing_client.last_seen = current_time
            existing_client.status = "online"
            
            await data_manager.update_client(existing_client)
            
            logger.info(f"Updated existing client: {existing_client.client_name} ({existing_client.hostname})")
            
            return BaseResponse(
                message=f"Client {existing_client.client_name} updated successfully"
            )
        else:
            # 创建新客户端
            new_client = ClientInfo(
                id=generate_id(),
                client_id=client_request.client_id,
                client_name=client_request.client_name,
                hostname=client_request.hostname,
                ip_address=client_request.ip_address,
                port=client_request.port,
                version=client_request.version,
                capabilities=client_request.capabilities,
                description=client_request.description,
                contact_info=client_request.contact_info,
                registered_at=current_time,
                last_seen=current_time,
                status="online"
            )
            
            # 保存到存储
            await data_manager.add_client(new_client)
            
            logger.info(f"Registered new client: {new_client.client_name} ({new_client.hostname})")
            
            return BaseResponse(
                message=f"Client {new_client.client_name} registered successfully"
            )
        
    except Exception as e:
        logger.error(f"Failed to register client: {e}")
        raise HTTPException(status_code=500, detail="Failed to register client")


@router.put("/clients/{client_id}/heartbeat", response_model=BaseResponse)
async def client_heartbeat(client_id: str):
    """客户端心跳更新"""
    try:
        client = await data_manager.get_client_by_id(client_id)
        
        if not client:
            raise HTTPException(status_code=404, detail="Client not found")
        
        # 更新最后见到时间和状态
        client.last_seen = time.time()
        client.status = "online"
        
        await data_manager.update_client(client)
        
        logger.debug(f"Client {client.client_name} heartbeat updated")
        
        return BaseResponse(
            message="Heartbeat updated successfully"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to update heartbeat for client {client_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to update heartbeat")


@router.delete("/clients/{client_id}", response_model=BaseResponse)
async def delete_client(client_id: str):
    """删除客户端"""
    try:
        # 检查客户端是否存在
        client = await data_manager.get_client_by_id(client_id)
        if not client:
            raise HTTPException(status_code=404, detail="Client not found")
        
        # 删除客户端
        await data_manager.delete_client(client_id)
        
        logger.info(f"Deleted client: {client.client_name} ({client.hostname})")
        
        return BaseResponse(
            message=f"Client {client.client_name} deleted successfully"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to delete client {client_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to delete client")


@router.get("/clients/{client_id}/subscriptions", response_model=BaseResponse)
async def get_client_subscriptions(client_id: str):
    """获取客户端的订阅信息"""
    try:
        # 检查客户端是否存在
        client = await data_manager.get_client_by_id(client_id)
        if not client:
            raise HTTPException(status_code=404, detail="Client not found")
        
        # 获取该客户端的订阅
        from .subscriptions import get_client_subscriptions as get_subs
        return await get_subs(client.client_id)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get subscriptions for client {client_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve client subscriptions")


async def get_pyolo_client_info() -> List[Dict[str, Any]]:
    """获取所有pyolo客户端信息"""
    try:
        clients = await data_manager.get_clients()
        pyolo_clients = []

        for client in clients:
            # 修复过滤条件：检查是否有YOLO相关能力或者是在线状态的客户端
            has_yolo_capabilities = any(cap in ["detection", "segmentation", "classification", "pose"]
                                     for cap in client.capabilities)
            is_pyolo_client = "yolo" in client.client_id.lower() or "pyolo" in client.client_id.lower()

            if client.status == "online" and (has_yolo_capabilities or is_pyolo_client):
                pyolo_clients.append({
                    "client_id": client.client_id,
                    "name": client.client_name,
                    "hostname": client.hostname,
                    "ip_address": client.ip_address,
                    "port": client.port,
                    "capabilities": client.capabilities,
                    "status": client.status
                })

        return pyolo_clients
    except Exception as e:
        logger.error(f"Failed to get pyolo clients: {e}")
        return []
